# -*- coding: utf-8 -*-

'''
@project : AIGateWay
@FileName: check_resp_util
@Author  :linych 
@Time    :2020/11/26 23:48
@Desc  : 
'''



from functools import wraps
import ailog
import time
from Core import SYS_CODE,mysql_log_loop
from Dao.t_ability_error_log_dao import insert_ability_error_log
import numpy as np
import datetime

class RespException(Exception):

    def __init__(self,code,msg,func='',detail=''):
        self.code = code
        self.msg = msg
        self.func = func
        self.detail = str(detail)

        try:
            self.__insert_error()
        except Exception as e :
            ailog.error('insert error : {}'.format(e))

    def __str__(self):
        return 'request error code:{} reason:{}'.format(self.code,self.msg)

    def __insert_error(self):
        mysql_log_loop.run(insert_ability_error_log(func=self.func,
                                            code=self.code,
                                            key_word=self.msg,
                                            message=self.detail,
                                            error_level=9,
                                            error_type=2,
                                            create_time=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')))





def asyn_check_resp(success_code,code_name='code',msg_name='msg'):
    success_code = np.array([success_code]).reshape(-1).tolist()

    def call(func):
        @wraps(func)
        async def wraper(*args,**kwargs):
            try:
                ailog.info('-- start {} '.format(func.__name__))
                start = time.time()
                res = await func(*args, **kwargs)
                if res[code_name] not in success_code:
                    raise RespException(code=res[code_name],msg=dict(res).get(msg_name,''),func=func.__name__,detail=res)
                end = time.time()
                ailog.info('-- end {} ,use time [{}]'.format(func.__name__,end-start))
                return res
            except Exception as e:
                ailog.error('Error {} reson: {}'.format(func.__name__,e))
                raise e

        return wraper
    return call
